package atom.core3.hibernate.util;

import java.util.Iterator;

import org.hibernate.CacheMode;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.engine.query.spi.sql.NativeSQLQueryScalarReturn;
import org.hibernate.internal.util.collections.ArrayHelper;

/**
 * hibernate 查询助手.
 * 
 * @author zhaomc 
 *
 */
@SuppressWarnings("unchecked")
public class QueryHelper extends HqlHelper {
	
	//zhaomc 增加 为了使用缓存
	private boolean ifCache=false;
	private boolean ifRefresh=false;
	public QueryHelper() {
		super();
	}	
	public QueryHelper(Class clazz) {
		super(clazz);
	}
	
	public QueryHelper(Class clazz, String alias) {
		super(clazz,alias);
	}	

	/**
	 * @param session
	 * @return
	 */
	public Query createQuery(Session session) {
		Query query = session.createQuery(hql.toString());
		if (ifCache) 
			query.setCacheable(true);
		if (ifRefresh)
			query.setCacheMode(CacheMode.REFRESH);
		
		query.setParameters(params.toArray(), ArrayHelper.toTypeArray(paramTypes));
				
		return query;
	}
	
	public SQLQuery createSQLQuery(Session session) {
		SQLQuery query =  session.createSQLQuery(hql.toString());
		if (ifCache) 
			query.setCacheable(true);
		if (ifRefresh)
			query.setCacheMode(CacheMode.REFRESH);		
		for (Iterator i = scalars.iterator(); i.hasNext();) {
			NativeSQLQueryScalarReturn scalar = (NativeSQLQueryScalarReturn) i.next();
			query.addScalar(scalar.getColumnAlias(), scalar.getType());
		}
		
		query.setParameters(this.getParams(), this.getParamTypes());
		
		return query;
	}
	
	public boolean isIfCache()
	{
		return ifCache;
	}

	public void setIfCache(boolean ifCache)
	{
		this.ifCache = ifCache;
	}

	public boolean isIfRefresh()
	{
		return ifRefresh;
	}

	public void setIfRefresh(boolean ifRefresh)
	{
		this.ifRefresh = ifRefresh;
	}
	
}
